<?php
/**
 * Created by PhpStorm.
 * User: xiaotao
 * Date: 18-5-3
 * Time: 下午5:20
 *
 */

namespace app\manage\controller;
use app\common\model\Config as ConfigM;
use app\common\model\Config as ConfigV;
use think\Request;

class Config  extends Base
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $list = ConfigM::select();
        $count = count($list);
        $data = [
            'items' => $list ?: [],
            'total' => $count
        ];
        return $this->result_json(null, 1, $data);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $config = new ConfigM();
        $data = $request->only(['label', 'key', 'type', 'value', 'prefix', 'sort', 'status']);
        if ($config->save($data)) {
            return $this->result_json('create success', 1, ['id' => $config->id]);
        } else {
            return $this->result_json('db error', 101);
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        // 字段验证和合法性验证
        $data = $request->only(['label', 'key', 'type', 'value', 'prefix', 'sort', 'status']);
        $config = ConfigM::get($id);    // 是否只查询单个字段
        if ($config) {
            if ($config->save($data) === false) {
                return $this->result_json('db error', 101);
            }
            return $this->result_json('update success', 1);
        } else {
            return $this->result_json('param error', 201);
        }
    }


    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id, $flag = 'true')
    {
        $data = [
            'status'    => $flag === 'true' ? -1 : 1
        ];
        // 是否现判断数据是否存在
        $config = new ConfigM();
        if ($config->save($data, compact('id')) === false) {
            return $this->result_json('db error', 101);
        }
        return $this->result_json('delete success', 1);

    }


}